<?php
/**
 * User:ayou chow
 * Date: 2020-02-01
 * Time: 14:34
 */

namespace app\common\model;


use think\facade\Cache;
use think\Model;

class LiveCategoryModel extends Model
{
    protected $connection = 'db_live';

    protected static function init()
    {
        LiveCategoryModel::afterInsert(function ($user) {
            Cache::store('redis')->rm('live_category_list');
        });
        LiveCategoryModel::afterUpdate(function ($user) {
            Cache::store('redis')->rm('live_category_list');
        });
        LiveCategoryModel::afterDelete(function ($user) {
            Cache::store('redis')->rm('live_category_list');
        });
    }

    public function categoryTop()
    {
        return $this->hasOne(LiveCategoryTopModel::class, 'id', 'category');
    }

    public static function lists(): array
    {
        return Cache::store('redis')->remember('live_category_list', function () {
            return static::select()->toArray();
        });
    }

    public static function getListByCategoryId(int $id): array
    {
        $data = [];
        foreach (static::lists() as $item) {
            if ($item['category'] == $id) {
                $data[] = $item;
            }
        }

        return $data;
    }
}